<?php

namespace app\mini\controller\driver;

use app\common\enum\account\PaymentPayeeType;
use app\common\enum\order\PayeeType;
use app\common\enum\order\PayStatus;
use app\common\enum\order\PayType;
use app\common\enum\order\ReasonType;
use app\common\enum\order\ReceiveType;
use app\common\exception\BaseException;
use app\common\model\AccountRecord;
use app\common\model\DeliveryLog;
use app\common\model\ReceiveLog;
use app\common\model\SalesmanStore;
use app\common\model\Store;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\common\controller\ApiController;
use app\common\enum\order\OrderStatus;
use app\common\enum\order\OrderType;
use app\common\model\CompanyWarehouse;
use app\common\traits\UploadTrait;
use app\company\model\AccountPaymentRecord;
use app\company\model\CompanyOrder;
use app\company\model\CompanyOrderDetail;
use app\company\model\CompanyTransferOrder;
use app\company\model\Delivery;
use app\company\model\DeliveryOrder;
use app\company\model\StoreBalanceLog;
use app\mini\model\RefundOrderInfo;
use app\Request;
use think\App;
use think\response\Json;
use app\mini\model\RefundOrderDetail;

/**
 * @ControllerAnnotation
 */
class Task extends ApiController
{
    use UploadTrait;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new CompanyOrder();
    }

    public function storeList(): Json
    {
        $get   = $this->request->get();
        if (empty($get['order_status'])) return $this->error('配送任务状态有误！');
        $where = [
            ['pid', '<>', 0],
            ['driver_id', '=', $this->uid],
            ['check_status', '=', 2]
        ];
        if (!empty($get['store'])) {
            $where[] = ['store_id', 'in', Store::where('name', 'like', '%' . $get['store'] . '%')->column('id')];
        }

        //统计
        $count = [
            'undone' => $this->model->where($where)->where('order_status', OrderStatus::BEING)->whereIn('order_type',[OrderType::SALES,OrderType::RETURN])->group('store_id')
                ->value('count(store_id)'),
            'done'   => $this->model->where($where)->where('order_status', OrderStatus::FINISH)->whereIn('order_type',[OrderType::SALES,OrderType::RETURN])->group('store_id')
                ->value('count(store_id)'),
            'undone_refund' => $this->model->where($where)->where('order_status', OrderStatus::BEING)->where('order_type',OrderType::RETURN)->group('store_id')
                ->value('count(store_id)'),
        ];

        if ($get['order_status'] == 3) { //配送中的退货单
            $where[] = ['order_type', '=', OrderType::RETURN];
            $where[] = ['order_status', '=', OrderStatus::BEING];

        }else{
            $where[] = ['order_type', 'in', [OrderType::SALES,OrderType::RETURN]];
            $where[] = ['order_status', '=', $get['order_status']];
        }

        $list = [];
        // 获取订单列表
        $this->model->field('*, sum(order_amount), sum(driver_money)')->where($where)->group('store_id')->select()
            ->each(function ($item) use (&$list, $where, $get) {
                // 获取该门店订单ids
                $where[]  = ['store_id', 'in', $item->store_id];
                $orderIds = $this->model->where($where)->column('id');
                if (!empty($get['lon']) && !empty($get['lat'])) {
                    $distance = distance($get['lon'], $get['lat']);
                } else {
                    $distance = "'位置未知' AS distance";
                }
                $storeInfo = Store::field("lon,lat,{$distance},name,contact,phone,address")
                    ->where('id', $item->store_id)->find();
                $list[]    = [
                    'store_id'     => $item->store_id,
                    'store'        => $storeInfo->name,
                    'lon'          => $storeInfo->lon,
                    'lat'          => $storeInfo->lat,
                    'contact'      => $storeInfo->contact,
                    'phone'        => $storeInfo->phone,
                    'address'      => $storeInfo->address,
                    'order_amount' => $item['sum(order_amount)'],
                    'orderIds'     => implode(',', $orderIds),
                    'order_num'    => count($orderIds),
                    'driver_money'    => $item['sum(driver_money)'],
                    'distance'     => $storeInfo['distance'],
                    'weight'       => 0,
                    'volume'       => 0
                ];
            });
        $local = (new CompanyWarehouse())->local($this->companyId);
        if (!$local) return $this->error('获取仓库位置失败，请联系管理员');
        $center = [
            'lng' => $local->lon,
            'lat' => $local->lat
        ];
        array_multisort(array_column($list, 'distance'), SORT_ASC, $list);
        return $this->success(compact('list', 'center', 'count'));
    }

    public function orderList(): Json
    {
        $get   = $this->request->get();
        $where = [
            ['pid', '<>', 0],

            ['driver_id', '=', $this->uid],
            ['store_id', '=', $get['store_id']],
        ];
        if (empty($get['order_status'])) return $this->error('配送任务状态有误！');
        if ($get['order_status'] == 3) {
            $where[] = ['order_status', '=', OrderStatus::BEING];
            $where[] = ['order_type', '=', OrderType::RETURN];
        }else{
            $where[] = ['order_status', '=', $get['order_status']];
            $where[] = ['order_type', 'in', [OrderType::SALES,OrderType::RETURN]];
        }
        // 获取订单列表
        $list = $this->model->where($where)->with([
            'detail' => function ($query) {
                $query->with([
                    'goods'      => function ($query) {
                        $query->field('id,name')->withTrashed();
                    },
                    'goods_spec' => function ($query) {
                        $query->field('id,name,unit,stock')->withTrashed();
                    },
                ]);
            },
            'dealer' => function ($query) {
                $query->field('id,name');
            },
            'delivery_log' => function ($query) {
                $query->field('id,company_order_id,money,image,remark,create_time');
            }
        ])->order('update_time desc')->append(['order_status_text'])->paginate($get['limit'] ?? 10);
        //        ->each(function ($item){
        //            $item->yc_money = 0;
        //            // 如果是预存款类型，查看业务员扣款到底扣了多少
        //            if ($item->receive_type == ReceiveType::YC) {
        //                $logInfo = (new StoreBalanceLog())->where('company_order_id', $item->id)->order('id asc')->find();
        //                $item->yc_money = bcsub($logInfo->old_balance,$logInfo->new_balance,2);
        //            }
        //        });
        return $this->success(compact('list'));
    }

    public function orderInfo(): Json
    {
        $get = $this->request->get();
        // 获取订单详情
        $info = $this->model->with([
            'detail'       => function ($query) {
                $query->with([
                    'goods'      => function ($query) {
                        $query->field('id,name')->withTrashed();
                    },
                    'goods_spec' => function ($query) {
                        $query->field('id,name,unit,stock,driver_money')->withTrashed();
                    },
                ]);
            },
            'delivery_log' => function ($query) {
                $query->field('id,company_order_id,money,image,remark');
            }
        ])->append(['order_status_text'])->find($get['order_id']);
        if ($info->delivery_log) {
            $info->delivery_log->image = explode(',', $info->delivery_log->image);
        } else {
            $info->delivery_log = ['id' => '', 'company_order_id' => '', 'money' => '', 'image' => [], 'remark' => ''];
        }
        $driverMoney = 0;
        foreach ($info->detail as $item) {
            $driverMoney += $item->goods_spec->driver_money * $item->num;
        }
        // 计算司机提成
        $info->driver_money = $driverMoney;
        $info->yc_money = 0;
        // 如果是预存款类型，查看业务员扣款到底扣了多少
        if ($info->receive_type == ReceiveType::YC) {
            $logInfo = (new StoreBalanceLog())->where('company_order_id', $info->id)->order('id asc')->find();
            $info->yc_money = bcsub($logInfo->old_balance, $logInfo->new_balance, 2);
        }
        return $this->success($info);
    }

    /**
     * @NodeAnnotation (title="司机端收款")
     * @param Request $request
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function pay(Request $request): Json
    {
        // 获取订单id，获取司机id，获取金额
        $this->checkPost();
        $post = $request->post();
        if (empty($post['goods']) || empty($post['delivery_amount'])) return $this->error('参数信息有误！');
        $info = $this->model->find($post['id']);
        if (!$info || $info->order_status != OrderStatus::BEING || !in_array($info->receive_type, [ReceiveType::NOW, ReceiveType::ZQ, ReceiveType::YC])) {
            return $this->error('订单信息有误！');
        }
        try {
            $this->model->transaction(function () use ($info, $post) {
                // 处理司机签收数量和金额
                $this->dealOrder($info, $post);
                $update = [
                    'order_status' => OrderStatus::FINISH
                ];
                $newInfo = $this->model->find($post['id']);
//                if ($newInfo->receive_type == ReceiveType::NOW) {
                if ($post['receive_type'] == ReceiveType::NOW) {
                    $update = $this->dealNow($newInfo, $post, $update);
                }
//                elseif($newInfo->receive_type == ReceiveType::ZQ){
                elseif($post['receive_type'] == ReceiveType::ZQ){
                    // 账期就只配送，司机提交拍照信息
                }
//                elseif ($newInfo->receive_type == ReceiveType::YC) {
                elseif ($post['receive_type'] == ReceiveType::YC) {
                    $update = $this->dealYc($newInfo, $post, $update);
                }
                // 修改子订单信息
                $son       = $parent = $update;
                $son['id'] = $post['id'];
                $this->model->update($son);
                // 修改主订单信息
                $parent['id'] = $newInfo->pid;
                $this->model->update($parent);
                // 组装配送信息
                $deliveryData = [
                    'company_id'        => $this->companyId,
                    'dealer_id'         => $newInfo['dealer_id'],
                    'store_id'          => $newInfo->store_id,
                    'driver_id'         => $this->uid,
                    'lon'               => $post['lon'] ?? '',
                    'lat'               => $post['lat'] ?? '',
                    'company_order_id'  => $post['id'],
                    'company_order_pid' => $newInfo->pid,
                    'receive_type'      => $post['receive_type'] ?? 0, // 1现结，2账期，3预存
                    'pay_type'          => $post['pay_type'] ?? 0, // 1现金，2对公，3挂账
                    'order_amount'      => $newInfo['order_amount'] ?? 0,
                    'delivery_amount'   => $newInfo['delivery_amount'] ?? 0,
                    'money'             => $post['money'] ?? 0,
                    'image'             => $post['image'],
                    'remark'            => $post['remark'] ?? '',
                ];
                (new DeliveryLog())->save($deliveryData);
                // 修改配送单状态
                $this->dealDelivery($post['id']);
                // 处理订单状态
                (new CompanyOrder())->where('id', $post['id'])->save(['delivery_status' => 4]);
            });
        } catch (\Exception $e) {
            return $this->error('配送签收失败' . '--' . $e->getMessage());
        }
        return $this->success('配送签收成功');
    }

    private function dealOrder($info, $post): void
    {
        // 不论什么订单状态，把司机签收的数量金额回填至订单和详情内
        $info->save(['delivery_amount' => $post['delivery_amount']]);
        $detailModel = new CompanyOrderDetail();
        $post['goods'] = json_decode($post['goods'], true);
        foreach ($post['goods'] as $goods) {
            $detail = $detailModel->find($goods['id']);
            if ($goods['delivery_num'] > $detail['num']) throw new BaseException(['message' => '签收数量不能大于订单数量']);
            $detail->save(['delivery_num' => $goods['delivery_num'], 'delivery_total_price' => bcmul($goods['delivery_num'], $detail->true_price, 2)]);
        }
    }

    private function dealNow($info, $post, $update): array
    {
        // 现结，要前端返回金额，判断是否支付完，提交拍照信息
        $payStatus = PayStatus::NOT_SETTLED;
        if ($post['money'] == $info['delivery_amount']) {
            $payStatus = PayStatus::SETTLED;
        } elseif ($post['money'] < $info['delivery_amount'] && $post['money'] > 0) {
            $payStatus = PayStatus::HALF_SETTLED;
        }
        $update['pay_amount']   = $post['money'];
        $update['pay_type']     = $post['pay_type'];
        $update['unsay_amount'] = $info->delivery_amount - $post['money'];
        $update['pay_status']   = $payStatus;
        // 2024.11.13 更新对账
        $accountModel = new AccountRecord();
        $accountInfo  = $accountModel->where('company_id', $this->companyId)
            ->where('payee_type', AccountRecord::DRIVER)
            ->where('payee_id', $this->uid)->find();
        $submitMoney  = $checkMoney = 0;
        if ($post['pay_type'] == PayType::CASH) {
            $submitMoney = $post['money'];
        } else if($post['pay_type'] == PayType::BANK){
            $checkMoney = $post['money'];
        }else if($post['pay_type'] == PayType::GZ){
            $post['money'] = 0;
        }
        if (!$accountInfo) {
            $accountData = [
                'company_id'   => $this->companyId,
                'payee_type'   => AccountRecord::DRIVER,
                'payee_id'     => $this->uid,
                'total_money'  => $post['money'] ?? 0,
                'real_money'   => 0,
                'submit_money' => $submitMoney,
                'check_money'  => $checkMoney,
            ];
            $accountModel->save($accountData);
            $accountId = $accountModel->getKey();
        } else {
            $accountInfo->inc('total_money', $post['money'])->inc('submit_money', $submitMoney)
                ->inc('check_money', $checkMoney)->save();
            $accountId = $accountInfo->id;
        }
        // 生成收款单列表信息
        $this->addAccountPaymentRecord($post, $accountId, $info);
        // 组装支付交易明细信息
        $payData = [
            'company_id'        => $this->companyId,
            'store_id'          => $info->store_id,
            'payee_type'        => PayeeType::DRIVER,
            'payee_id'          => $this->uid,
            'company_order_id'  => $post['id'],
            'company_order_pid' => $info->pid,
            'pay_type'          => $post['pay_type'],
            'reason'            => ReasonType::ORDER,
            'money'             => $post['money'] ?? 0,
            'image'             => $post['image'],
            'remark'            => $post['remark'] ?? '',
            'account_record_id' => $accountId,
        ];
        (new ReceiveLog())->save($payData);
        return $update;
    }

    /**
     * 添加账户付款记录
     */
    private function addAccountPaymentRecord(mixed $post, mixed $accountId, mixed $info): void
    {
        if ($post['pay_type'] == PayType::BANK) {
            (new AccountPaymentRecord())->save([
                'no'         => generateOrderNo('SK'),
                'company_id' => $this->companyId,
                'account_id' => $accountId,
                'payee_type' => PaymentPayeeType::DRIVER,
                'payee_id'   => $this->uid,
                'store_id'   => $info->store_id,
                'amount'     => $post['money'],
                'channel'    => '公司账户款项',
                'pay_type'   => PayType::BANK,
                'remark'     => $post['remark'] ?? '',
                'voucher'    => $post['image'] ?? '',
            ]);
        }
//        if ($post['yc_pay_type'] == PayType::BANK) {
//            (new AccountPaymentRecord())->save([
//                'no'         => generateOrderNo('SK'),
//                'company_id' => $this->companyId,
//                'account_id' => $accountId,
//                'payee_type' => PaymentPayeeType::DRIVER,
//                'payee_id'   => $this->uid,
//                'store_id'   => $info->store_id,
//                'amount'     => $post['yc_money'],
//                'channel'    => '公司账户款项',
//                'pay_type'   => PayType::BANK,
//                'remark'     => $post['remark'] ?? '',
//                'voucher'    => $post['image'] ?? '',
//            ]);
//        }
    }

    private function dealYc($newInfo, $post, $update): array
    {
        // 预存要扣减冻结的钱，然后司机提交拍照信息
        $update['pay_amount']   = $newInfo->delivery_amount;
        $update['unsay_amount'] = 0;
        $update['pay_status']   = PayStatus::SETTLED;
        // 修改门店业务员的冻结金额
        $ssInfo = SalesmanStore::where('salesman_id', $newInfo->salesman_id)
            ->where('store_id', $newInfo->store_id)->find();
        $oldBalance = $ssInfo->balance;
        $oldFreeze = $ssInfo->freeze;
        // 记录门店余额变动情况
        // 判断金额大小
        if ($newInfo->yc_money >= $newInfo->delivery_amount) {
            // 签收金额小于已付预存款金额，回退预存款
            $diffMoney = bcsub($newInfo->yc_money, $newInfo->delivery_amount, 2);
            $ssInfo->dec('freeze', $newInfo->yc_money)->inc('balance', $diffMoney)->save();
            $balanceLogData = [
                'company_id' => $this->companyId,
                'salesman_id' => $newInfo->salesman_id,
                'store_id' => $newInfo->store_id,
                'creator_type' => StoreBalanceLog::TYPE_DRIVER,
                'creator_id' => $this->uid,
                'company_order_id' => $newInfo->id,
                'old_balance' => $oldBalance,
                'new_balance' => bcadd($oldBalance, $diffMoney, 2),
                'old_freeze' => $oldFreeze,
                'new_freeze' => bcsub($oldFreeze, $newInfo->yc_money, 2),
                'remark' => StoreBalanceLog::REMARK_SIGN,
            ];
        } else if ($newInfo->yc_money < $newInfo->delivery_amount) {
            // 签收金额大于已付预存款金额，司机收款
            $ssInfo->dec('freeze', $newInfo->yc_money)->save();
            $balanceLogData = [
                'company_id' => $this->companyId,
                'salesman_id' => $newInfo->salesman_id,
                'store_id' => $newInfo->store_id,
                'creator_type' => StoreBalanceLog::TYPE_DRIVER,
                'creator_id' => $this->uid,
                'company_order_id' => $newInfo->id,
                'old_balance' => $oldBalance,
                'new_balance' => $oldBalance,
                'old_freeze' => $oldFreeze,
                'new_freeze' => bcsub($oldFreeze, $newInfo->yc_money, 2),
                'remark' => StoreBalanceLog::REMARK_SIGN,
            ];
            // 司机收款
            /*$accountModel = new AccountRecord();
            $accountInfo  = $accountModel->where('company_id', $this->companyId)
                ->where('payee_type', AccountRecord::DRIVER)
                ->where('payee_id', $this->uid)->find();
            $submitMoney  = $checkMoney = 0;
            if ($post['yc_pay_type'] == PayType::CASH) {
                $submitMoney = $post['money'];
            } else {
                $checkMoney = $post['money'];
            }
            if (!$accountInfo) {
                $accountData = [
                    'company_id'   => $this->companyId,
                    'payee_type'   => AccountRecord::DRIVER,
                    'payee_id'     => $this->uid,
                    'total_money'  => $post['money'] ?? 0,
                    'real_money'   => 0,
                    'submit_money' => $submitMoney,
                    'check_money'  => $checkMoney,
                ];
                $accountModel->save($accountData);
                $accountId = $accountModel->getKey();
            } else {
                $accountInfo->inc('total_money', $post['money'])->inc('submit_money', $submitMoney)
                    ->inc('check_money', $checkMoney)->save();
                $accountId = $accountInfo->id;
            }
            // 生成收款单列表信息
            $this->addAccountPaymentRecord($post, $accountId, $newInfo);
            // 组装支付交易明细信息
            $payData = [
                'company_id'        => $this->companyId,
                'store_id'          => $newInfo->store_id,
                'payee_type'        => PayeeType::DRIVER,
                'payee_id'          => $this->uid,
                'company_order_id'  => $post['id'],
                'company_order_pid' => $newInfo->pid,
                'pay_type'          => $post['pay_type'],
                'reason'            => ReasonType::ORDER,
                'money'             => $post['yc_money'] ?? 0,
                'image'             => $post['image'],
                'remark'            => $post['remark'] ?? '',
                'account_record_id' => $accountId,
            ];
            (new ReceiveLog())->save($payData);*/
        }
        if (isset($balanceLogData)) (new StoreBalanceLog())->save($balanceLogData);
        return $update;
    }

    private function dealDelivery($orderId): void
    {
        $deliveryModel = new Delivery();
        $deliveryOrderModel = new DeliveryOrder();
        $detail = $deliveryOrderModel->where('company_order_id', $orderId)->order('id desc')->find();
        if (!$detail) return;
        // 处理配送单和配送单详情状态
        $deliveryOrderModel->where('company_order_id', $orderId)->save(['delivery_status' => 2]);
        $no_delivery_count = $deliveryOrderModel->where('delivery_id', $detail->delivery_id)->where('delivery_status', 1)->count();
        $no_delivery_count ? $delivery_status = 2 : $delivery_status = 3;
        $deliveryModel->where('id', $detail->delivery_id)->save(['status' => $delivery_status]);

    }

    /**
     * 司机确认访单回库申请
     */
    public function orderReturn()
    {
        $param = $this->request->post();
        if (empty($param['order_id']) || empty($param['detail'])) return $this->error('参数信息有误！');
        //参数过滤
        $order_info = (new CompanyOrder)->where(['id' => $param['order_id'], 'driver_id' => $this->uid])->find($param['order_id']);
        if (empty($order_info)) return $this->error('获取订单信息失败！');
        if ($order_info['order_status'] != OrderStatus::BEING || $order_info['order_type'] != OrderType::RETURN || $order_info['delivery_status'] == 4) return $this->error('订单信息有误！');
        //退货数量是否过滤
        //创建记录
        try {
            $this->model = new RefundOrderInfo();
            $this->joinAddTable = 'orderDetail';
            $this->model->transaction(function () use ($param, $order_info) {
                $insert_data = json_decode($param['detail'],true);
                //默认入主仓
                //$warehouse_id = (new CompanyWarehouse())->where(['company_id' => $this->companyId, 'type' => 1, 'status' => 1])->limit(1)->value('id') ?? 0;
                $warehouse_id = 0;
                $product_num = array_sum(array_column($insert_data, 'transfer_num'));
                $cate_num    = count(array_unique(array_column($insert_data, 'dealer_goods_id')));
                //添加记录
                $insert = [
                    'store_id' => $order_info['store_id'],
                    'company_id' => $this->companyId,
                    'dealer_id' => $order_info['dealer_id'],
                    'company_order_id' => $order_info['id'],
                    'driver_id' => $this->uid,
                    'warehouse_id' => $warehouse_id,
                    'product_num' => $product_num,
                    'cate_num' => $cate_num,
                    'status' => RefundOrderInfo::STATUS_WAIT,
                    'remark' => $param['remark'] ?? '',
                    'image' => $param['image'] ?? '',
                ];
                $this->model->save($insert);
                $refund_id = $this->model->id;
                $insert_data = array_map(function ($item) use ($refund_id) {
                    if(!empty($item['item_id'])) {
                        (new CompanyOrderDetail())->where('id',$item['item_id'])->update(['delivery_num'=>$item['transfer_num']]);
                    }
                    $item['ro_id'] = $refund_id;
                    $item['cod_id'] = $item['item_id'];
                    unset($item['item_id']);
                    return $item;

                }, $insert_data);
                $this->joinAddTable(['orderDetail' => json_encode($insert_data)]);
                //(new RefundOrderDetail())->saveAll($insert_data);
                // 组装配送信息
                $deliveryData = [
                    'company_id'        => $this->companyId,
                    'dealer_id'         => $order_info['dealer_id'],
                    'store_id'          => $order_info['store_id'],
                    'driver_id'         => $this->uid,
                    'lon'               => $param['lon'] ?? '',
                    'lat'               => $param['lat'] ?? '',
                    'company_order_id'  => $order_info['id'],
                    'company_order_pid' => $order_info['pid'],
                    'receive_type'      => 0, // 1现结，2账期，3预存
                    'pay_type'          => 0, // 1现金，2对公，3挂账
                    'order_amount'      => 0,
                    'delivery_amount'   => 0,
                    'money'             => 0,
                    'image'             => $param['image'] ?? '',
                    'remark'            => $param['remark'] ?? '',
                ];
                (new DeliveryLog())->save($deliveryData);

                // 修改配送单状态
                $this->dealDelivery($param['order_id']);
                //修改订单状态
                (new CompanyOrder())->where('id', $param['order_id'])->save(['delivery_status' => 4, 'order_status' => OrderStatus::FINISH]);
            });

        } catch (\Exception $e) {
            return $this->error('签收失败' . '--' . $e->getMessage());
        }
        return $this->success('退单商品签收成功');
    }

    /**
     * 司机访单回库单列表
     */
    public function returnOrderList()
    {
        $param = $this->request->get();
        $where ['driver_id'] = $this->uid;
        $where ['company_id'] = $this->companyId;
        if (!empty($param['status'])) $where ['status'] = $param['status'];
        $list = (new RefundOrderInfo())->where($where)->with([
            'store'=>function($query){
                $query->field('id,name');
            },'order_info'=>function($query){
                $query->field('id,order_no');
            },
        ])->order('id desc')->select()->toArray();
        return $this->success($list);
    }

    /**
     * 司机访单回库单详情
     */
    public function refundOrderDetail() {
        $param = $this->request->get();
        if (empty($param['id'])) return $this->error('参数信息有误！');
        $where = [
            'id' => $param['id'],
            'driver_id' => $this->uid,
        ];
        $info =  (new RefundOrderInfo())->where($where)->with([
            'store'=>function($query){
                $query->field('id,name');
            },
            'order_info'=>function($query){
                $query->field('id,order_no');
            },
            'order_detail' => function ($query) {
                $query->with([
                    'goods' => function ($query) {
                        $query->field('id,name')->withTrashed();
                    },
                    'goods_spec' => function ($query) {
                        $query->field('id,name,unit')->withTrashed();
                    },
                ]);
            }
        ])->find();
        return $this->success($info);
    }

    /**
     * 司机创建入仓调拨单
     * @return Json
     */
    public function addReturn(Request $request): Json
    {
        $param = $request->post();
        if (empty($param['ids']) || empty($param['warehouse_id'])) return $this->error('参数信息有误！');
        //订单基本信息
        $ids = explode(',', $param['ids']);
        $list = (new RefundOrderInfo())->whereIn('id', $ids)->where(['driver_id' => $this->uid, 'status' => 1, 'company_id' => $this->companyId])->with(['order_detail'])->select()->toArray();
        if (empty($list)) return $this->error('获取订单信息失败！');
        //仓库
        $warehouse_info = (new CompanyWarehouse())->where(['id'=>$param['warehouse_id'],'company_id'=>$this->companyId,'type' => 1, 'status' => 1])->find();
        if (empty($warehouse_info)) return $this->error('获取仓库信息失败！');
        //创建
        $insert = [];
        $insert['order_no'] = generateOrderNo('DB');
        $insert['apply_user_id'] = $this->uid;
        $insert['transfer_mode'] = 1;
        $insert['transfer_type'] = 4;
        //todo 经销商是否会不同
        $insert['dealer_id'] = $list[0]['dealer_id'];
        $insert['end_warehouse_id'] = $param['warehouse_id'];
        $insert['start_warehouse_id'] = $this->uid;
        $insert['company_id'] = $this->companyId;
        $insert['isTrusted'] = true;
        $insert['remark'] = $param['remark'] ?? '';
        $detail = [];
        $product_num = 0;
        $product_list = [];
        foreach ($list as $list_value) {
            foreach ($list_value['order_detail'] as $value) {
                if (!empty($value)) {
                    $product_num += $value['transfer_num'];
                    $product_list[] = $value['dealer_goods_id'];
                    $detail[] = [
                        'transfer_num' => $value['transfer_num'],
                        'dealer_goods_id' => $value['dealer_goods_id'],
                        'dealer_goods_spec_id' => $value['dealer_goods_spec_id'],
                    ];
                }
            }
        }
        $insert['product_num'] = $product_num;
        $insert['cate_num'] = count(array_unique($product_list));
        $insert['detail'] = json_encode($detail);
        try {
            $this->model = new CompanyTransferOrder();
            $this->model->transaction(function () use ($insert, $ids) {
                $this->model->save($insert);
                //todo 库存暂不修改
                // 如果有需要添加的关联表数据
                $this->joinAddTable = 'detail';
                $this->joinAddTable($insert);
                //关联修改
                (new RefundOrderInfo())->whereIn('id', $ids)->update(['status' => RefundOrderInfo::STATUS_OK]);
            });
        } catch (\Exception $e) {
            return $this->error('新增失败:' . $e->getMessage());
        }
        return $this->success('新增成功');
    }

    /**
     * 司机访单回库订单列表
     */
    public function transferOrderList()
    {
        // 组合查询参数
        $param = $this->request->get();
        $limit = $param['limit'] ?? 10;
        $where = [
            'transfer_type' => 4,
            'start_warehouse_id' => $this->uid,
            'apply_user_id' => $this->uid,
        ];

        // 获取列表数据
        $sql = (new CompanyTransferOrder())->with(['endW'])->where($where)->order('id','desc');
        if (!empty($param['check_status'])) {
            if ($param['check_status'] == 1) {
                $sql->where('check_status',$param['check_status']);
            }
            if ($param['check_status'] == 2) {
                $sql->whereIn('check_status',[2,3]);
            }
        }
        if (!empty($param['order_no'])) {
            $sql->where('order_no', 'like', '%' . $param['order_no'] . '%');
        }
        $list = $sql->paginate($limit)->toArray();
        //统计角标
        if ($param['check_status'] == '1'){
            $list['wait_num'] = $list['total'];
            $list['success_num'] = (new CompanyTransferOrder())->where($where)->whereIn('check_status',[2,3])->count();
        }
        if ($param['check_status'] == '2'){
            $list['success_num'] = $list['total'];
            $list['wait_num'] = (new CompanyTransferOrder())->where($where)->where('check_status',1)->count();
        }
        return $this->success($list);
    }

    /**
     * 司机访单回库订单详情
     */
    public function transferOrderDetail()
    {
        $param = $this->request->param();
        if (empty($param['id'])) return $this->error('参数信息有误！');
        $info = (new CompanyTransferOrder())->where(['id' => $param['id'], 'transfer_type' => 4])->with(['endW', 'detail' => function ($item) {
            $item->with([
                'goods' => function ($query) {
                    $query->field('id,name')->withTrashed();
                },
                'goods_spec' => function ($query) {
                    $query->field('id,name,unit')->withTrashed();
                },
            ]);
        }])->find();
        return $this->success($info);

    }

    /**
     * 公司仓库列表
     */
    public function warehouseList()
    {
        $list = (new CompanyWarehouse())->field('id,name,no')->where(['company_id' => $this->companyId, 'type' => 1, 'status' => 1])->order('id','desc')->select()->toArray();
        return $this->success($list);
    }


}
